package com.pond.pond.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pond.common.core.domain.R;
import com.pond.common.core.web.controller.BaseController;
import com.pond.common.core.web.domain.AjaxResult;
import com.pond.common.core.web.page.TableDataInfo;
import com.pond.common.security.utils.SecurityUtils;
import com.pond.pond.domain.AppVersion;
import com.pond.pond.domain.CommunityPost;
import com.pond.pond.domain.CommunityPostComment;
import com.pond.pond.domain.FishingTechnique;
import com.pond.pond.domain.FishingTechniqueComment;
import com.pond.pond.domain.UpdateLog;
import com.pond.pond.domain.dto.CheckUpdateRequest;
import com.pond.pond.domain.dto.UpdateLogRequest;
import com.pond.pond.domain.vo.AppVo;
import com.pond.pond.domain.vo.FishingTechniqueVo;
import com.pond.pond.service.AppService;
import com.pond.pond.service.IAppVersionService;
import com.pond.pond.service.ICommunityPostService;
import com.pond.pond.service.IFishingTechniqueService;
import com.pond.pond.service.IUpdateLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/app")
public class AppController extends BaseController {

    @Autowired
    private AppService appService;

    @Autowired
    private IFishingTechniqueService fishingTechniqueService;

    @Autowired
    private IAppVersionService appVersionService;

    @Autowired
    private IUpdateLogService updateLogService;

    @Autowired
    private ICommunityPostService communityPostService;

    /**
     * 查询钓场列表（供APP端使用）
     * @param userLatitude 用户纬度
     * @param userLongitude 用户经度
     */
    @GetMapping("/fishingSpot/list")
    public AjaxResult list(@RequestParam(required = false) BigDecimal userLatitude,
                           @RequestParam(required = false) BigDecimal userLongitude) {
        List<AppVo> list = appService.selectFishingSpotList(userLatitude, userLongitude);
        return AjaxResult.success(list);
    }

    /**
     * 查询钓场详情（供APP端使用）
     * @param id 钓场ID
     * @param userLatitude 用户纬度
     * @param userLongitude 用户经度
     */
    @GetMapping("/fishingSpot/{id}")
    public AjaxResult getInfo(@PathVariable Long id,
                              @RequestParam(required = false) BigDecimal userLatitude,
                              @RequestParam(required = false) BigDecimal userLongitude) {
        AppVo appVo = appService.selectFishingSpotById(id, userLatitude, userLongitude);
        return AjaxResult.success(appVo);
    }

    /**
     * 钓位预约签到
     * @param bookingId 预约ID
     */
    @GetMapping("/checkin/{bookingId}")
    public AjaxResult checkin(@PathVariable Long bookingId) {
        boolean result = appService.checkinBooking(bookingId);
        return result ? AjaxResult.success("签到成功") : AjaxResult.error("签到失败");
    }

    // ==================== 钓技学堂接口 ====================

    /**
     * 获取钓技文章列表
     */
    @GetMapping("/fishing/technique/list")
    public TableDataInfo getTechniqueList(FishingTechnique fishingTechnique) {
        startPage();
        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            // 未登录用户
        }
        
        List<FishingTechniqueVo> list = fishingTechniqueService.selectFishingTechniqueListWithUser(fishingTechnique, userId);
        return getDataTable(list);
    }

    /**
     * 获取钓技文章详情
     */
    @GetMapping("/fishing/technique/{id}")
    public AjaxResult getTechniqueDetail(@PathVariable Long id) {
        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            // 未登录用户
        }
        
        FishingTechniqueVo technique = fishingTechniqueService.selectFishingTechniqueDetailById(id, userId);
        return AjaxResult.success(technique);
    }

    @PostMapping("/fishing/technique")
    public AjaxResult addTechnique(@RequestBody String requestBody) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> requestMap = objectMapper.readValue(requestBody, Map.class);

            // ✅ 解码 content 字段
            String rawContent = (String) requestMap.get("content");
            if (rawContent != null) {
                String decodedContent = URLDecoder.decode(rawContent, StandardCharsets.UTF_8.name());
                requestMap.put("content", decodedContent);
            }

            // 构建 FishingTechnique 实体对象
            FishingTechnique fishingTechnique = new FishingTechnique();
            fishingTechnique.setTitle((String) requestMap.get("title"));
            fishingTechnique.setSubtitle((String) requestMap.get("subtitle"));
            fishingTechnique.setContent((String) requestMap.get("content")); // 已解码
            fishingTechnique.setImageUrl((String) requestMap.get("imageUrl"));
            fishingTechnique.setCategory((String) requestMap.get("category"));
            fishingTechnique.setDifficulty((String) requestMap.get("difficulty"));
            fishingTechnique.setTags((String) requestMap.get("tags"));
            fishingTechnique.setAuthor((String) requestMap.get("author"));
            fishingTechnique.setEstimatedReadTime(requestMap.get("estimatedReadTime") != null ?
                    Integer.valueOf(requestMap.get("estimatedReadTime").toString()) : null);
            fishingTechnique.setSortOrder(requestMap.get("sortOrder") != null ?
                    Integer.valueOf(requestMap.get("sortOrder").toString()) : null);
            fishingTechnique.setStatus((String) requestMap.get("status"));
            fishingTechnique.setRemark((String) requestMap.get("remark"));

            int result = fishingTechniqueService.insertFishingTechnique(fishingTechnique);
            return result > 0
                    ? AjaxResult.success("新增成功", fishingTechnique.getId())
                    : AjaxResult.error("新增失败");

        } catch (Exception e) {
            logger.error("创建钓技文章失败", e);
            return AjaxResult.error("新增失败：" + e.getMessage());
        }
    }

    /**
     * 更新钓技文章
     */
    @PutMapping("/fishing/technique")
    public AjaxResult editTechnique(@RequestBody String requestBody) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();

            // 临时将字符串解析为 Map
            Map<String, Object> requestMap = objectMapper.readValue(requestBody, Map.class);

            // 对 content 字段做 URL 解码
            String rawContent = (String) requestMap.get("content");
            String decodedContent = URLDecoder.decode(rawContent, StandardCharsets.UTF_8.name());
            requestMap.put("content", decodedContent);

            // 构建实体对象
            FishingTechnique fishingTechnique = new FishingTechnique();
            fishingTechnique.setId(requestMap.get("id") != null ? Long.valueOf(requestMap.get("id").toString()) : null);
            fishingTechnique.setTitle((String) requestMap.get("title"));
            fishingTechnique.setSubtitle((String) requestMap.get("subtitle"));
            fishingTechnique.setContent((String) requestMap.get("content")); // 已是解码后的
            fishingTechnique.setImageUrl((String) requestMap.get("imageUrl"));
            fishingTechnique.setCategory((String) requestMap.get("category"));
            fishingTechnique.setDifficulty((String) requestMap.get("difficulty"));
            fishingTechnique.setTags((String) requestMap.get("tags"));
            fishingTechnique.setAuthor((String) requestMap.get("author"));
            fishingTechnique.setEstimatedReadTime(requestMap.get("estimatedReadTime") != null ?
                    Integer.valueOf(requestMap.get("estimatedReadTime").toString()) : null);
            fishingTechnique.setSortOrder(requestMap.get("sortOrder") != null ?
                    Integer.valueOf(requestMap.get("sortOrder").toString()) : null);
            fishingTechnique.setStatus((String) requestMap.get("status"));
            fishingTechnique.setRemark((String) requestMap.get("remark"));

            return toAjax(fishingTechniqueService.updateFishingTechnique(fishingTechnique));
        } catch (Exception e) {
            logger.error("更新钓技文章失败", e);
            return AjaxResult.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除钓技文章
     */
    @DeleteMapping("/fishing/technique/{ids}")
    public AjaxResult removeTechnique(@PathVariable Long[] ids) {
        return toAjax(fishingTechniqueService.deleteFishingTechniqueByIds(ids));
    }

    /**
     * 更新文章状态
     */
    @PutMapping("/fishing/technique/changeStatus")
    public AjaxResult changeStatus(@RequestBody FishingTechnique fishingTechnique) {
        return toAjax(fishingTechniqueService.updateFishingTechnique(fishingTechnique));
    }

    /**
     * 点赞/取消点赞文章
     */
    @PostMapping("/fishing/technique/{id}/like")
    public AjaxResult likeTechnique(@PathVariable Long id) {
        Long userId = SecurityUtils.getUserId();
        Map<String, Object> result = fishingTechniqueService.toggleLike(id, userId);
        return AjaxResult.success("操作成功", result);
    }

    /**
     * 收藏/取消收藏文章
     */
    @PostMapping("/fishing/technique/{id}/favorite")
    public AjaxResult favoriteTechnique(@PathVariable Long id) {
        Long userId = SecurityUtils.getUserId();
        Map<String, Object> result = fishingTechniqueService.toggleFavorite(id, userId);
        return AjaxResult.success("操作成功", result);
    }

    /**
     * 获取用户收藏列表
     */
    @GetMapping("/fishing/technique/favorites")
    public TableDataInfo getUserFavorites() {
        startPage();
        Long userId = SecurityUtils.getUserId();
        List<FishingTechniqueVo> list = fishingTechniqueService.selectUserFavorites(userId);
        return getDataTable(list);
    }

    /**
     * 获取文章评论列表
     */
    @GetMapping("/fishing/technique/{id}/comments")
    public TableDataInfo getTechniqueComments(@PathVariable Long id) {
        startPage();
        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            // 未登录用户
        }
        
        List<FishingTechniqueComment> list = fishingTechniqueService.selectCommentsByTechniqueId(id, userId);
        return getDataTable(list);
    }

    /**
     * 发表评论
     */
    @PostMapping("/fishing/technique/{id}/comment")
    public AjaxResult addComment(@PathVariable Long id, @RequestBody FishingTechniqueComment comment) {
        Long userId = SecurityUtils.getUserId();
        comment.setTechniqueId(id);
        comment.setUserId(userId);
        
        Long commentId = fishingTechniqueService.addComment(comment);
        comment.setId(commentId);
        return AjaxResult.success("评论成功", comment);
    }

    /**
     * 删除评论
     */
    @DeleteMapping("/fishing/technique/comment/{id}")
    public AjaxResult deleteComment(@PathVariable Long id) {
        Long userId = SecurityUtils.getUserId();
        boolean result = fishingTechniqueService.deleteComment(id, userId);
        return result ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    /**
     * 点赞/取消点赞评论
     */
    @PostMapping("/fishing/technique/comment/{id}/like")
    public AjaxResult likeComment(@PathVariable Long id) {
        Long userId = SecurityUtils.getUserId();
        Map<String, Object> result = fishingTechniqueService.toggleCommentLike(id, userId);
        return AjaxResult.success("操作成功", result);
    }

    /**
     * 增加文章阅读量
     */
    @PostMapping("/fishing/technique/{id}/read")
    public AjaxResult incrementReadCount(@PathVariable Long id) {
        int readCount = fishingTechniqueService.incrementReadCount(id);
        Map<String, Object> result = new HashMap<>();
        result.put("readCount", readCount);
        return AjaxResult.success("操作成功", result);
    }

    /**
     * 获取文章统计信息
     */
    @GetMapping("/fishing/technique/{id}/stats")
    public AjaxResult getTechniqueStats(@PathVariable Long id) {
        Map<String, Object> stats = fishingTechniqueService.getArticleStats(id);
        return AjaxResult.success("查询成功", stats);
    }

    /**
     * 获取热门文章
     */
    @GetMapping("/fishing/technique/hot")
    public AjaxResult getHotTechniques(@RequestParam(defaultValue = "10") Integer limit,
                                       @RequestParam(defaultValue = "read") String type) {
        List<FishingTechniqueVo> list = fishingTechniqueService.selectHotTechniques(limit, type);
        return AjaxResult.success("查询成功", list);
    }

    /**
     * 获取所有分类
     */
    @GetMapping("/fishing/technique/categories")
    public AjaxResult getCategories() {
        List<Map<String, Object>> categories = fishingTechniqueService.selectCategoryStats();
        return AjaxResult.success("查询成功", categories);
    }

    /**
     * 获取热门标签
     */
    @GetMapping("/fishing/technique/tags")
    public AjaxResult getHotTags(@RequestParam(defaultValue = "20") Integer limit) {
        List<Map<String, Object>> tags = fishingTechniqueService.selectHotTags(limit);
        return AjaxResult.success("查询成功", tags);
    }

    /**
     * 获取用户的钓技评论
     */
    @GetMapping("/user/comments/techniques")
    public TableDataInfo getUserTechniqueComments(@RequestParam(defaultValue = "1") Integer pageNum,
                                                  @RequestParam(defaultValue = "20") Integer pageSize) {
        startPage();
        Long userId = SecurityUtils.getUserId();
        List<Map<String, Object>> list = fishingTechniqueService.selectUserCommentsWithTechniqueTitle(userId);
        return getDataTable(list);
    }

    // ==================== 社区模块接口 ====================

    /**
     * 获取社区帖子列表
     */
    @GetMapping("/community/posts")
    public R<List<CommunityPost>> getCommunityPosts(CommunityPost communityPost) {
        startPage();
        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            // 未登录用户
        }
        
        List<CommunityPost> list = communityPostService.selectCommunityPostList(communityPost, userId);
        return R.ok(list);
    }

    /**
     * 获取社区帖子详情
     */
    @GetMapping("/community/posts/{id}")
    public R<CommunityPost> getCommunityPostDetail(@PathVariable Long id) {
        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            // 未登录用户
        }
        
        CommunityPost post = communityPostService.selectCommunityPostById(id, userId);
        if (post == null) {
            return R.fail("帖子不存在");
        }
        return R.ok(post);
    }

    /**
     * 发布社区帖子
     */
    @PostMapping("/community/posts")
    public R<Long> createCommunityPost(@RequestBody CommunityPost communityPost) {
        try {
            // 解码 content 字段
            if (communityPost.getContent() != null) {
                String decodedContent = URLDecoder.decode(communityPost.getContent(), StandardCharsets.UTF_8.name());
                communityPost.setContent(decodedContent);
            }
            
            // 设置作者ID
            Long userId = SecurityUtils.getUserId();
            communityPost.setAuthorId(userId);
            
            // 显式设置中国时区的创建时间
            ZonedDateTime chinaTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
            Date createTime = Date.from(chinaTime.toInstant());
            communityPost.setCreateTime(createTime);
            communityPost.setUpdateTime(createTime);
            
            // 初始化计数器
            communityPost.setLikeCount(0);
            communityPost.setCommentCount(0);
            communityPost.setReadCount(0);
            
            // 设置默认值
            if (communityPost.getStatus() == null) {
                communityPost.setStatus("1");
            }
            if (communityPost.getIsTop() == null) {
                communityPost.setIsTop(0);
            }
            if (communityPost.getSortOrder() == null) {
                communityPost.setSortOrder(0);
            }

            int result = communityPostService.insertCommunityPost(communityPost);
            return result > 0
                    ? R.ok(communityPost.getId(), "发布成功")
                    : R.fail("发布失败");

        } catch (Exception e) {
            logger.error("发布社区帖子失败", e);
            return R.fail("发布失败：" + e.getMessage());
        }
    }

    /**
     * 更新社区帖子
     */
    @PutMapping("/community/posts")
    public R<String> updateCommunityPost(@RequestBody CommunityPost communityPost) {
        try {
            // 解码 content 字段
            if (communityPost.getContent() != null) {
                String decodedContent = URLDecoder.decode(communityPost.getContent(), StandardCharsets.UTF_8.name());
                communityPost.setContent(decodedContent);
            }

            int result = communityPostService.updateCommunityPost(communityPost);
            return result > 0 ? R.ok("更新成功") : R.fail("更新失败");
        } catch (Exception e) {
            logger.error("更新社区帖子失败", e);
            return R.fail("更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除社区帖子
     */
    @DeleteMapping("/community/posts/{ids}")
    public R<String> deleteCommunityPost(@PathVariable Long[] ids) {
        int result = communityPostService.deleteCommunityPostByIds(ids);
        return result > 0 ? R.ok("删除成功") : R.fail("删除失败");
    }

    /**
     * 点赞/取消点赞帖子
     */
    @PostMapping("/community/posts/{id}/like")
    public R<Map<String, Object>> likeCommunityPost(@PathVariable Long id) {
        Long userId = SecurityUtils.getUserId();
        Map<String, Object> result = communityPostService.toggleLike(id, userId);
        return R.ok(result, "操作成功");
    }

    /**
     * 收藏/取消收藏帖子
     */
    @PostMapping("/community/posts/{id}/favorite")
    public R<Map<String, Object>> favoriteCommunityPost(@PathVariable Long id) {
        Long userId = SecurityUtils.getUserId();
        Map<String, Object> result = communityPostService.toggleFavorite(id, userId);
        return R.ok(result, "操作成功");
    }

    /**
     * 增加帖子阅读量
     */
    @PostMapping("/community/posts/{id}/read")
    public R<Map<String, Object>> incrementPostReadCount(@PathVariable Long id) {
        int readCount = communityPostService.incrementReadCount(id);
        Map<String, Object> result = new HashMap<>();
        result.put("readCount", readCount);
        return R.ok(result, "操作成功");
    }

    /**
     * 获取帖子评论列表
     */
    @GetMapping("/community/posts/{id}/comments")
    public R<List<CommunityPostComment>> getCommunityPostComments(@PathVariable Long id) {
        startPage();
        Long userId = null;
        try {
            userId = SecurityUtils.getUserId();
        } catch (Exception e) {
            // 未登录用户
        }
        
        List<CommunityPostComment> list = communityPostService.selectCommentsByPostId(id, userId);
        return R.ok(list);
    }

    /**
     * 发表帖子评论
     */
    @PostMapping("/community/posts/{id}/comment")
    public R<CommunityPostComment> addCommunityPostComment(@PathVariable Long id, @RequestBody CommunityPostComment comment) {
        Long userId = SecurityUtils.getUserId();
        comment.setPostId(id);
        comment.setUserId(userId);
        comment.setStatus("1"); // 默认已发布状态
        comment.setLikeCount(0);
        
        // 显式设置中国时区的创建时间
        ZonedDateTime chinaTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
        Date createTime = Date.from(chinaTime.toInstant());
        comment.setCreateTime(createTime);
        comment.setUpdateTime(createTime);
        
        Long commentId = communityPostService.addComment(comment);
        comment.setId(commentId);
        return R.ok(comment, "评论成功");
    }

    /**
     * 回复帖子评论
     */
    @PostMapping("/community/posts/{postId}/comment/{parentId}/reply")
    public R<CommunityPostComment> replyCommunityPostComment(@PathVariable Long postId, 
                                                            @PathVariable Long parentId, 
                                                            @RequestBody CommunityPostComment comment) {
        Long userId = SecurityUtils.getUserId();
        comment.setPostId(postId);
        comment.setUserId(userId);
        comment.setParentId(parentId);
        comment.setStatus("1"); // 默认已发布状态
        comment.setLikeCount(0);
        
        // 显式设置中国时区的创建时间
        ZonedDateTime chinaTime = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
        Date createTime = Date.from(chinaTime.toInstant());
        comment.setCreateTime(createTime);
        comment.setUpdateTime(createTime);
        
        Long commentId = communityPostService.addComment(comment);
        comment.setId(commentId);
        return R.ok(comment, "回复成功");
    }

    /**
     * 删除帖子评论
     */
    @DeleteMapping("/community/posts/comment/{id}")
    public R<String> deleteCommunityPostComment(@PathVariable Long id) {
        Long userId = SecurityUtils.getUserId();
        boolean result = communityPostService.deleteComment(id, userId);
        return result ? R.ok("删除成功") : R.fail("删除失败");
    }

    /**
     * 点赞/取消点赞评论
     */
    @PostMapping("/community/posts/comment/{id}/like")
    public R<Map<String, Object>> likeCommunityPostComment(@PathVariable Long id) {
        Long userId = SecurityUtils.getUserId();
        Map<String, Object> result = communityPostService.toggleCommentLike(id, userId);
        return R.ok(result, "操作成功");
    }

    /**
     * 获取热门帖子
     */
    @GetMapping("/community/posts/hot")
    public R<List<CommunityPost>> getHotCommunityPosts(@RequestParam(defaultValue = "10") Integer limit,
                                          @RequestParam(defaultValue = "read") String type) {
        List<CommunityPost> list = communityPostService.selectHotPosts(limit, type);
        return R.ok(list, "查询成功");
    }

    /**
     * 获取用户收藏的帖子
     */
    @GetMapping("/community/posts/favorites")
    public R<List<CommunityPost>> getUserFavoritePosts() {
        startPage();
        Long userId = SecurityUtils.getUserId();
        List<CommunityPost> list = communityPostService.selectUserFavorites(userId);
        return R.ok(list);
    }

    /**
     * 获取用户发布的帖子
     */
    @GetMapping("/community/posts/my")
    public R<List<CommunityPost>> getUserPosts() {
        startPage();
        Long userId = SecurityUtils.getUserId();
        List<CommunityPost> list = communityPostService.selectUserPosts(userId);
        return R.ok(list);
    }

    /**
     * 获取用户的社区评论
     */
    @GetMapping("/user/comments/posts")
    public R<List<Map<String, Object>>> getUserPostComments(@RequestParam(defaultValue = "1") Integer pageNum,
                                                           @RequestParam(defaultValue = "20") Integer pageSize) {
        startPage();
        Long userId = SecurityUtils.getUserId();
        List<Map<String, Object>> list = communityPostService.selectUserCommentsWithPostTitle(userId);
        return R.ok(list);
    }

    // ==================== 版本更新接口 ====================

    /**
     * 检查版本更新
     */
    @PostMapping("/version/check-update")
    public AjaxResult checkUpdate(@Valid @RequestBody CheckUpdateRequest request, HttpServletRequest httpRequest) {
        try {
            // 记录检查更新日志
            UpdateLogRequest logRequest = new UpdateLogRequest();
            logRequest.setDeviceId(request.getDeviceId());
            logRequest.setCurrentVersion(request.getCurrentVersion());
            logRequest.setTargetVersion("unknown"); // 检查阶段暂时未知
            logRequest.setUpdateStatus("checking");
            
            String ipAddress = getClientIpAddress(httpRequest);
            String userAgent = httpRequest.getHeader("User-Agent");
            updateLogService.recordUpdateLog(logRequest, ipAddress, userAgent);
            
            // 检查更新
            Map<String, Object> result = appVersionService.checkUpdate(request);
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("检查版本更新失败", e);
            return AjaxResult.error("检查更新失败：" + e.getMessage());
        }
    }

    /**
     * 记录更新日志
     */
    @PostMapping("/version/update-log")
    public AjaxResult recordUpdateLog(@Valid @RequestBody UpdateLogRequest request, HttpServletRequest httpRequest) {
        try {
            String ipAddress = getClientIpAddress(httpRequest);
            String userAgent = httpRequest.getHeader("User-Agent");
            
            Long logId = updateLogService.recordUpdateLog(request, ipAddress, userAgent);
            
            Map<String, Object> result = new HashMap<>();
            result.put("logId", logId);
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("记录更新日志失败", e);
            return AjaxResult.error("记录日志失败：" + e.getMessage());
        }
    }

    /**
     * 获取版本历史（管理端）
     */
    @GetMapping("/admin/versions")
    public TableDataInfo getVersionHistory(AppVersion appVersion) {
        startPage();
        List<AppVersion> list = appVersionService.selectAppVersionList(appVersion);
        return getDataTable(list);
    }

    /**
     * 获取版本详情（管理端）
     */
    @GetMapping("/admin/versions/{id}")
    public AjaxResult getVersionDetail(@PathVariable Long id) {
        try {
            AppVersion appVersion = appVersionService.selectAppVersionById(id);
            if (appVersion == null) {
                return AjaxResult.error("版本信息不存在");
            }
            return AjaxResult.success("查询成功", appVersion);
        } catch (Exception e) {
            logger.error("获取版本详情失败", e);
            return AjaxResult.error("获取版本详情失败：" + e.getMessage());
        }
    }

    /**
     * 发布新版本（管理端）
     */
    @PostMapping("/admin/versions")
    public AjaxResult publishVersion(@Valid @RequestBody AppVersion appVersion) {
        try {
            int result = appVersionService.publishVersion(appVersion);
            if (result > 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("id", appVersion.getId());
                data.put("versionCode", appVersion.getVersionCode());
                return AjaxResult.success("发布成功", data);
            } else {
                return AjaxResult.error("发布失败");
            }
        } catch (Exception e) {
            logger.error("发布版本失败", e);
            return AjaxResult.error("发布失败：" + e.getMessage());
        }
    }

    /**
     * 修改版本信息（管理端）
     */
    @PutMapping("/admin/versions")
    public AjaxResult updateVersion(@Valid @RequestBody AppVersion appVersion) {
        return toAjax(appVersionService.updateAppVersion(appVersion));
    }

    /**
     * 删除版本（管理端）
     */
    @DeleteMapping("/admin/versions/{ids}")
    public AjaxResult removeVersions(@PathVariable Long[] ids) {
        return toAjax(appVersionService.deleteAppVersionByIds(ids));
    }

    /**
     * 设置为最新版本（管理端）
     */
    @PutMapping("/admin/versions/{id}/latest")
    public AjaxResult setAsLatestVersion(@PathVariable Long id) {
        return toAjax(appVersionService.setAsLatestVersion(id));
    }

    /**
     * 获取更新日志列表（管理端）
     */
    @GetMapping("/admin/update-logs")
    public TableDataInfo getUpdateLogs(UpdateLog updateLog) {
        startPage();
        List<UpdateLog> list = updateLogService.selectUpdateLogList(updateLog);
        return getDataTable(list);
    }

    /**
     * 删除更新日志（管理端）
     */
    @DeleteMapping("/admin/update-logs/{ids}")
    public AjaxResult removeUpdateLogs(@PathVariable Long[] ids) {
        try {
            int result = updateLogService.deleteUpdateLogByIds(ids);
            return result > 0 ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
        } catch (Exception e) {
            logger.error("删除更新日志失败", e);
            return AjaxResult.error("删除失败：" + e.getMessage());
        }
    }


    /**
     * 获取设备更新轨迹（管理端）
     */
    @GetMapping("/admin/device/{deviceId}/update-history")
    public AjaxResult getDeviceUpdateHistory(@PathVariable String deviceId) {
        List<UpdateLog> history = updateLogService.getDeviceUpdateHistory(deviceId);
        return AjaxResult.success("查询成功", history);
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0];
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
}
